package com.lambkit.core.task;

import com.lambkit.core.LifecycleException;
import com.lambkit.core.LifecycleState;

/**
 * @author yangyong(孤竹行)
 */
public class TaskInstance<C extends TaskContext<T>, T extends BaseTask> implements ITaskInstance<C, T> {
    private C context;

    public TaskInstance(C context) {
        this.context = context;
    }

    public TaskInstance runOn(C context) {
        this.context = context;
        return this;
    }

    @Override
    public void start() throws LifecycleException {
        if(context != null && context.isReady()) {
            context.setCurrentState(LifecycleState.STARTING);
            T task = context.getTask();
            task.getPipLine().invoke(context);
            context.setCurrentState(LifecycleState.STARTED);
            context.percent(100, "任务执行完成");
        }
    }

    @Override
    public void stop() throws LifecycleException {
        context.setCurrentState(LifecycleState.STOPPED);
    }

    public C getContext() {
        return context;
    }

    public void setContext(C context) {
        this.context = context;
    }

    @Override
    public String getId() {
        return this.context.getId();
    }

    @Override
    public LifecycleState getCurrentState() {
        return this.context.getCurrentState();
    }
}
